package com.bootdo.cash.service.impl;

import static com.bootdo.common.utils.ShiroUtils.getUserId;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.cash.dao.CashDao;
import com.bootdo.cash.domain.CashDO;
import com.bootdo.cash.service.ExamineService;
import com.bootdo.common.config.Constant;
import com.bootdo.common.redis.lock.CommonRedisLock;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.mq.RabbitUtil;
import com.bootdo.order.dao.RechargeDao;
import com.bootdo.order.domain.RechargeDO;
import com.bootdo.payee.dao.PayeeAgentDao;
import com.bootdo.payee.domain.PayeeAgentDO;
import com.bootdo.system.dao.UserRoleDao;

/**
 * @Desc
 * @date 2019/12/24
 *
 */
@Service
public class ExamineServiceImpl implements ExamineService {

    private static final Logger logger = LoggerFactory.getLogger(ExamineServiceImpl.class);

    @Autowired
    private CashDao cashMapper;
    @Autowired
    private UserRoleDao userRoleMapper;
    @Autowired
    private RechargeDao rechargeMapper;
    @Autowired
    private PayeeAgentDao payeeAgentMapper;
    @Autowired
    private RabbitUtil rabbitUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public RechargeDO get(Long id){
        return rechargeMapper.get(id);
    }

    /**
     * 提现审核列表
     * @param map
     * @return
     */
    @Override
    public List<RechargeDO> list(Map<String, Object> map){
        //格式话日期
        String startDate = (String) map.get("startTime");
        String endDate = (String) map.get("endTime");
        if (StringUtils.isNotBlank(startDate)){
            startDate = DateUtils.getDateOfFormatByYMD(startDate, DateUtils.DATE_PATTERN_YMD,DateUtils.DATE_B_TIME_PATTERN);
            endDate = DateUtils.getDateOfFormatByYMD(endDate, DateUtils.DATE_PATTERN_YMD,DateUtils.DATE_E_TIME_PATTERN);
            map.put("startTime", startDate);
            map.put("endTime", endDate);
        }
        //获取用户权限
        int checkUserIsManager = userRoleMapper.checkUserIsManager(getUserId());
        if (checkUserIsManager != 1){
            map.put("userId", getUserId());
        }
        return rechargeMapper.list(map);
    }

    @Override
    public int count(Map<String, Object> map){
        return rechargeMapper.count(map);
    }

    /**
     * 修改审核状态
     * @param recharge
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public int update(RechargeDO recharge) {
        CommonRedisLock commonLock = new CommonRedisLock(stringRedisTemplate, "EXAMINE_UPDATE_" + recharge.getId());
        try {
            if (commonLock.tryLock(3)) {
                int status = recharge.getStatus();
                recharge = rechargeMapper.get(recharge.getId());
                logger.debug("获取用户提现数据：" + JSONObject.toJSONString(recharge));
                if (0 != recharge.getStatus().intValue()) {
                    return -2;
                }

                //审核通过，提现/收款金额实际到账字段更改
                CashDO cash = cashMapper.get(recharge.getCashId());
                logger.debug("获取用户申请提现数据：" + JSONObject.toJSONString(cash));
                long lockingMoney = Math.round(cash.getLockingMoney() * 100);
                long money = Math.round(recharge.getMoney() * 100);

                DecimalFormat df = new DecimalFormat("0.00");
                cash.setLockingMoney(Double.valueOf(df.format((float) (lockingMoney - money) / 100)));
                if (1 == status){
                    long actualMoney = Math.round(cash.getActualArrival() * 100);
                    cash.setActualArrival(Double.valueOf(df.format((float) (money + actualMoney) / 100)));
                    //验证用户是否为平台用户
                    int i = userRoleMapper.checkUserIsManager(recharge.getUserId());
                    if (1 != i) {
                        //为收款户代理恢复额度
                        PayeeAgentDO payeeAgent = payeeAgentMapper.get(recharge.getUserId());
                        JSONObject object = new JSONObject();
                        object.put("date", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                        object.put("orderId", "TC0001");
                        object.put("type", 1);
                        object.put("reason", "充值恢复额度");
                        object.put("money", recharge.getMoney());
                        object.put("userId", payeeAgent.getUserId());
                        rabbitUtil.sendToQueue(Constant.UPDATE_QUOTA, object.toJSONString());
                    }
                    long cashMoney = Math.round(cash.getCashMoney() * 100);
                    actualMoney = Math.round(cash.getActualArrival() * 100);
                    if ((cashMoney - actualMoney) <= 0) {
                        cash.setStatus(2);
                    }
                }
                cashMapper.update(cash);
                recharge.setStatus(status);
                commonLock.unlock();
                return rechargeMapper.update(recharge);
            }
        } catch (Exception e) {
            commonLock.unlock();
            logger.error("用户提现修改审核状态异常"+e);
            return 0;
        }
        return 0;
    }
}
